# -*- coding: UTF-8 -*-

# Copyright (C) 2009 Daniele Favara.
# Written by Daniele Favara <daniele@zeroisp.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import atom
atom.MEMBER_STRING_ENCODING = unicode
import gdata.photos.service
import gdata.media
import gdata.geo
import gdata.photos

import os, sys
import simplejson, urllib

from misc import unicode_urlencode,unicode_urldecode

FLASHVARS = "host=picasaweb.google.com&RGB=0x000000&feed=%s"

"""
http://code.google.com/intl/it-IT/apis/picasaweb/developers_guide_protocol.html
"""

class PicasaGoogleCom(object):
    def __init__(self, email=None,
                         password=None,
                         account_type="GOOGLE",
                         user=None,
                         thumbsizes=['32c'],
                         imgmax = "320"
                         ):
        self.email = email
        self.password = password
        self.account_type = account_type
        self.user = user
        self.thumbsizes = thumbsizes
        self.imgmax = imgmax
        self.gd_client = gdata.photos.service.PhotosService(
                                         email=self.email,
                                         password = self.password,
                                         account_type = self.account_type)

        self.gd_client.source = 'tgzeroisp-piacasa'
        self.gd_client.ProgrammaticLogin()
        self.feed_url = '/data/feed/api/user/default/'
        self.entry_url = '/data/entry/api/user/default/'

    def get_album(self, albumid):
        feed_url = self.feed_url + 'albumid/%s?kind=photo&imgmax=%s&thumbsize=%s' % (
                                                                            albumid,
                                                                            self.imgmax,
                                                                            ','.join(self.thumbsizes))
        return self.gd_client.GetFeed(feed_url)

    def get_album_entry(self, albumid):
        entry_url = self.entry_url + 'albumid/%s?kind=photo&imgmax=%s&thumbsize=%s' % (
                                                                            albumid,
                                                                            self.imgmax,
                                                                            ','.join(self.thumbsizes))
        return self.gd_client.GetEntry(entry_url)

    def get_photo(self, albumid, photoid):
        feed_url = self.feed_url + 'albumid/%s/photoid/%s' % (albumid,photoid)
        return self.gd_client.GetFeed(feed_url)

    def update_photo(self, photo):
        return self.gd_client.UpdatePhotoMetadata(photo)

    def get_albums(self):
        feed_url = self.feed_url + '?kind=album&thumbsize=%s' % ','.join(self.thumbsizes)
        p = self.gd_client.GetFeed(feed_url)
        albums = {}
        for entry in p.entry:

            albums[entry.gphoto_id.text] = dict(title=entry.title.text,
                                                name=entry.name.text,
                                                published=entry.published.text,
                                                link0=entry.link[0].href,
                                                link1=entry.link[1].href,
                                                link2=entry.link[2].href,
                                                albumid=entry.gphoto_id.text,
                                                summary=entry.summary.text,
                                                rights=entry.rights.text,
                                                updated=entry.updated.text,
                                                location=entry.location.text,
                                                numphotos=entry.numphotos.text,
                                                )
            geo_pos=entry.geo.Point.pos.text
            lng = None
            lat = None
            if geo_pos:
                lng, lat = geo_pos.split()
            albums[entry.gphoto_id.text]['lng'] = lng
            albums[entry.gphoto_id.text]['lat'] = lat
            urlbase, urlquery = urllib.splitquery(albums[entry.gphoto_id.text]['link0'])
            params = {}
            if urlquery:
                params = unicode_urldecode(urlquery)
            params['kind'] = "photo"
            params['alt'] = 'rss'
            url = "%s?%s"%(urlbase,
                           unicode_urlencode(params))
            albums[entry.gphoto_id.text]['flashvars'] = FLASHVARS %(urllib.quote(url, safe=';'))
            for thumb in entry.media.thumbnail:
                pass
        return albums

    def update_album(self, album):
        updated_album = self.gd_client.Put(album, album.GetEditLink().href,
                                      converter=gdata.photos.AlbumEntryFromString)

    def delete_album(self, albumid):
        try:
            entry_url = self.entry_url + 'albumid/%s?kind=album' % (albumid)
            album = self.gd_client.GetEntry(str(entry_url))
            self.gd_client.Delete(album)
            return True
        except:
            raise

    def insert_album(self, title, summary, location='', access='private'):
        return self.gd_client.InsertAlbum(title=title,
                                          summary=summary, location=location,
                                          access=access)

    def insert_photo(self, album, handle, title='', summary='', keywords=None ):
        return self.gd_client.InsertPhotoSimple(album, title, summary, handle,
                                                 keywords=keywords)

if __name__ == '__main__':
    p = PicasaGoogleCom()
    #print p.insert_album('title', 'summary').id.text
    #ret =
    print p.get_albums()

    print p.gd_client.auth_token
    #ret = p.delete_album('5319916749131005857')
    #ret = p.get_albums()
    from pprint import pprint
    #print ret.icon.text
    #for i in ret.entry:
    #    print i
    #for i in dir(ret):
    #    if not i.startswith('_'):
    #        print i, getattr(ret, i)
    #        break

